const router = require('koa-router')(); //注意：引入的方式
const db = require('../utils/database.js')

router.prefix('/dishes')

router.get('/', ctx => {
	ctx.body = "dishes--index";
})


//////////////////////////////
// 文件上传
const multer = require('@koa/multer') // 引入
// 单域多文件上传
const storage = multer.diskStorage({
	destination: function(req, file, cb) {
		cb(null, './public/upload')
	},
	filename: function(req, file, cb) {
		const ext = file.originalname.split('.').pop()
		const newName = 'qtj-' + Date.now() + '.' + ext
		cb(null, newName)
	}
})
const upload = multer({ // 源码中multer是一个函数，所以需要执行
	storage
})
// upload.array(global.fileName, maxCount) 参数二为上传文件的最大数量
router.post('/upload', upload.array('icon', 5), ctx => {
	// console.log(ctx.files);
	// ctx.files 可获取到上传的所有文件信息，type -> Array
	const data = ctx.files.map(file => ({ filename: file.filename, size: file.size }))
	ctx.body = { success: true, code: 20000, message: "文件上传成功,数量为" + ctx.files.length, data }
})
/////////////////////////////////////


// 查询 分页 搜索 排序
router.get('/list', async ctx => {
	const { order, by, page = 0, pageSize = 20, query, query1 } = ctx.request.query // request可省略
	let sort = {},
		where = {}
	if (by) {
		sort[by] = order // by是条件 order是-1或1
	}
	if (query) { // 菜品名称
		where.name = { $regex: new RegExp(query) }
	}
	if (query1) { // 菜品分类
		where.classify = { $regex: new RegExp(query1) }
	}
	const data = await db.find('dishes', { where, sort, skip: page * pageSize, limit: pageSize })
	//总条数
	const total = await db.total('dishes', where)
	const datas = await db.find('classify', where)
	ctx.body = { success: true, code: 20000, message: "数据查询成功", data, total, datas }
})

// 新增
router.post('/save', async ctx => {
	const { classify, desc, measure, name, picture, price, recommend } = ctx.request.body;
	const data = await db.insert('dishes', {
		classify,
		desc,
		measure,
		name,
		picture,
		price,
		recommend,
		time: Date.now()
	})
	ctx.body = { success: true, code: 20000, message: "数据新增成功", data }
})

// 修改
router.post('/modify', async ctx => {
	const { classify, desc, measure, name, picture, price, recommend, _id } = ctx.request.body
	const data = await db.update('dishes', { _id }, {
		classify,
		desc,
		measure,
		name,
		picture,
		price,
		recommend,
		time: Date.now()
	})
	ctx.body = { success: true, code: 20000, message: "数据修改成功", data }
})

// 删除
router.get('/delete', async ctx => {
	const { _id } = ctx.request.query
	const data = await db.delete('dishes', { _id })
	ctx.body = { success: true, code: 20000, message: "数据删除成功", data }
})

module.exports = router
